"""
简化的数据库设置向导
"""

import os
import sys
import asyncio
import json
from pathlib import Path

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

async def main():
    print("=== MindMate 数据库设置向导 ===")
    print("这个向导将帮助你设置Supabase数据库")
    
    # 检查现有数据
    print("\\n1. 检查现有数据...")
    
    data_dir = Path("./data")
    sessions_file = data_dir / "sessions.json"
    roles_file = data_dir / "roles.json"
    
    sessions_count = 0
    roles_count = 0
    messages_count = 0
    
    if sessions_file.exists():
        with open(sessions_file, 'r', encoding='utf-8') as f:
            sessions = json.load(f)
        sessions_count = len(sessions)
        for session in sessions.values():
            messages_count += len(session.get('messages', []))
        print(f"找到 {sessions_count} 个会话")
    
    if roles_file.exists():
        with open(roles_file, 'r', encoding='utf-8') as f:
            roles = json.load(f)
        roles_count = len(roles)
        print(f"找到 {roles_count} 个自定义角色")
    
    print(f"数据概览: {sessions_count} 个会话, {roles_count} 个角色, {messages_count} 条消息")
    
    if sessions_count == 0 and roles_count == 0:
        print("没有找到数据，无需迁移")
        return
    
    # 获取Supabase配置
    print("\\n2. 请提供Supabase配置信息")
    print("需要先在 https://supabase.com 创建项目")
    print("然后在 Settings > API 中获取以下信息:")
    
    supabase_url = input("\\nSupabase URL (https://xxx.supabase.co): ").strip()
    supabase_key = input("Supabase anon key: ").strip()
    
    if not supabase_url or not supabase_key:
        print("配置信息不能为空")
        return
    
    # 设置环境变量
    os.environ['SUPABASE_URL'] = supabase_url
    os.environ['SUPABASE_ANON_KEY'] = supabase_key
    
    print("\\n3. 测试数据库连接...")
    
    try:
        from database.supabase_client import check_supabase_config, test_connection
        
        if not check_supabase_config():
            print("[ERROR] 配置检查失败")
            return
            
        print("[OK] 配置检查通过")
        
        if not test_connection():
            print("[ERROR] 数据库连接失败")
            return
            
        print("[OK] 数据库连接成功")
        
    except Exception as e:
        print(f"[ERROR] 测试连接出错: {e}")
        return
    
    # 显示SQL脚本
    print("\\n4. 创建数据库表")
    print("请在Supabase SQL编辑器中执行以下脚本:")
    print("=" * 60)
    
    init_sql_path = Path("database/init.sql")
    if init_sql_path.exists():
        with open(init_sql_path, 'r', encoding='utf-8') as f:
            print(f.read())
    else:
        print("未找到 init.sql 文件")
        return
    
    print("=" * 60)
    
    input("\\n执行完SQL脚本后，按回车继续...")
    
    # 开始迁移
    print("\\n5. 开始数据迁移...")
    
    try:
        from migrate_to_database import DataMigrator
        
        migrator = DataMigrator(str(data_dir), force=False)
        success = await migrator.migrate()
        
        if success:
            print("[SUCCESS] 数据迁移完成!")
            print("\\n迁移统计:")
            print(f"会话: {migrator.stats['sessions_migrated']} 个")
            print(f"消息: {migrator.stats['messages_migrated']} 条")
            print(f"角色: {migrator.stats['roles_migrated']} 个")
            
            if migrator.stats['errors']:
                print(f"\\n错误: {len(migrator.stats['errors'])} 个")
        else:
            print("[ERROR] 数据迁移失败")
            
    except Exception as e:
        print(f"[ERROR] 迁移过程出错: {e}")
        import traceback
        traceback.print_exc()
    
    print("\\n6. 设置完成!")
    print("现在你的数据已经保存在Supabase数据库中")
    print("可以在Supabase Dashboard中查看和管理")

if __name__ == "__main__":
    asyncio.run(main())